package pt.ipleiria.estg.es2.byinvitationonly;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import pt.ipleiria.estg.es2.byinvitationonly.modelo.Contacto;


public class MainActivity extends Activity {

    public static final int PEDIDO_CONTACTO = 1;
    boolean checkIn=false;
    private MenuItem item;
    private Contacto contacto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        item = menu.findItem(R.id.action_im_here);
        obterContactoUser();

        return true;
    }

    private void obterContactoUser() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String nome = prefs.getString(getString(R.string.pref_name), "");
        String email = prefs.getString(getString(R.string.pref_email), "");

        contacto=new Contacto(nome, email);
    }

    private void colocarContactoUser(Contacto contacto) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = prefs.edit();

        editor.putString(getString(R.string.pref_name), contacto.getNome());
        editor.putString(getString(R.string.pref_email), contacto.getEmail());

        editor.apply();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_im_here) {
            invertCheckIn(item);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void invertCheckIn(final MenuItem item) {
        if(checkIn == false){
            obterContactoUser();
            if(contacto != null && !contacto.getNome().isEmpty() && !contacto.getEmail().isEmpty()){
                mostrarJanelaConfirmacao(item);
            }
            else{
                mostrarJanelaPedidoPreenchimento();
               //Toast.makeText(this, getString(R.string.dados_incompletos), Toast.LENGTH_SHORT).show();
            }
        }
        else{
            checkIn = false;
            item.setIcon(R.drawable.ic_action_alone);
        }
    }

    private void mostrarJanelaPedidoPreenchimento() {
        AlertDialog.Builder construtor = new AlertDialog.Builder(this);

        construtor.setTitle(R.string.dados_incompletos);
        construtor.setMessage(R.string.mensagem_completar_dados);
        construtor.setPositiveButton(R.string.general_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                abrirActivitySolicitacaoDados();
            }
        });
        construtor.setNegativeButton(R.string.general_no, null);
        construtor.create().show();
    }

    private void abrirActivitySolicitacaoDados() {
        Intent i = new Intent(this, ContactSettingsActivity.class);
        startActivityForResult(i, PEDIDO_CONTACTO);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==PEDIDO_CONTACTO){
            if(contacto != null && !contacto.getNome().isEmpty() && !contacto.getEmail().isEmpty()){
                mostrarJanelaConfirmacao(item);
            }
        }
    }

    private void mostrarJanelaConfirmacao(final MenuItem item) {
        AlertDialog.Builder construtor = new AlertDialog.Builder(this);

        construtor.setTitle(R.string.confirmacao).setMessage("Tem a certeza que pretende partilhar " +
                "os dados?\n" + "Nome: " + contacto.getNome() + "Email: " +
                contacto.getEmail())
                .setNegativeButton(getString(R.string.general_no), null)
                .setPositiveButton(getString(R.string.general_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (temRede()) {
                            checkIn = true;
                            item.setIcon(R.drawable.ic_action_together);

                            Intent intent = new Intent(MainActivity.this, WhoIsHereActivity.class);
                            intent.putExtra(WhoIsHereActivity.IS_CHECKED_IN, checkIn);
                            startActivity(intent);
                        } else {
                            showConnectivityError();
                        }
                    }
                });

        construtor.show();
    }

    private void showConnectivityError() {
        AlertDialog.Builder constructor = new AlertDialog().Builder(this);
        constructor.setTitle(getString(R.string.erro)).setMessage(getString(R.string.sem_rede))
                .setPositiveButton(getString(R.string.ok), null)
                .create().show();

    }

    private boolean temRede() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isConnectedOrConnecting());
    }
}
